import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/constant/constant.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import '../../../constant/EcyEventConsnt.dart';
import '../../../ecycommon/EcyEventBus.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../ecycommon/utils/EcyUserUtil.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../../login/common/DateUtil.dart';
import '../model/CommodityTop.dart';
import 'package:easy_image_viewer/easy_image_viewer.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class EcyNewGoodsView extends StatefulWidget {
  late _EcyNewGoodsViewState state;

  EcyNewGoodsView({required super.key});

  @override
  State<StatefulWidget> createState() {
    state = _EcyNewGoodsViewState();
    return state;
  }

  reloadData(String search) {
    state._refreshData(search);
  }
}

class _EcyNewGoodsViewState extends State<EcyNewGoodsView> {
  _EcyNewGoodsViewState();

  final RefreshController _refreshController1 = RefreshController(initialRefresh: false);
  final RefreshController _refreshController2 = RefreshController(initialRefresh: false);

  // int _total = 0;
  // int _page = 1;
  int _currentPage = 1;
  bool _hasMore = false;

  final List<int> indexList = List.filled(19, 0);
  final List<CommodityTop> _commodityTopList = [];

  @override
  void initState() {
    super.initState();
    initNotis();
    _refreshData("");
  }

  initNotis() {
    EcyEventBus().on(EcyEventConst.kHttpConnected, (arg) {
      _refreshData("");
    });
  }

  //无数据时下拉刷新
  Future<void> _onRefresh1() async {
    _currentPage = 1;
    print("下拉操作1");
    await _refreshData("");
    // 重置上拉加载状态
    _refreshController1.refreshCompleted();
  }

  //下拉刷新
  Future<void> _onRefresh2() async {
    _currentPage = 1;
    await _refreshData("");
    _refreshController2.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshController2.loadComplete();
    } else {
      _refreshController2.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading2() async {
    if (_hasMore) {
      _currentPage++;
      await _refreshData("");
      _refreshController2.loadComplete();
    } else {
      _refreshController2.loadNoData();
    }
  }

  Future<void> _refreshData(String search) async {
    try {
      Map<String, dynamic> body = {
        "pageIndex": _currentPage,
        "pageSize": 2,
        "search": search,
      };
      var response = await EcyRequestbasemanager().get("/app/api/app/top/top", body);
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<CommodityTop> commonPage =
              EcyApiCommonPage.fromJson(response["data"], (json) => CommodityTop.fromJson(json));
          // _total = commonPage.pages ?? 0;
          // _page = commonPage.current ?? 0;
          _hasMore = (commonPage.pages ?? 0) > _currentPage;
          _currentPage = commonPage.current ?? 0;
          var commodityTopList = commonPage.records ?? [];
          if (_currentPage == 1) {
            _commodityTopList.clear();
          }
          setState(() {
            _commodityTopList.addAll(commodityTopList);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取上新失败$e");
    }
  }

  Future<void> _onLike(CommodityTop commodityTop) async {
    try {
      var loginFlag = await EcyUserUtil.logined();
      if (loginFlag) {
        var response = await EcyRequestbasemanager().post('/app/api/app/top/support/${commodityTop.id}', {});
        if (response != null) {
          var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
          if (commonResponse.code != 0 && commonResponse.code != 200) {
            EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
          }

          bool likeFlag = commodityTop.currentUserSupport == 1;

          setState(() {
            commodityTop.supports = (commodityTop.supports ?? 0) + (likeFlag ? -1 : 1);
            commodityTop.currentUserSupport = likeFlag ? 0 : 1;
          });
        }
      } else {
        EasyLoading.showToast("请先登录", duration: const Duration(seconds: 1));
      }
    } catch (e) {
      EcyLogger.log("点赞失败$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget headImage = Image.asset("assets/images/ic_head.jpg");

    if (_commodityTopList.isEmpty) {
      return Container(
          color: const Color(0xFFF5F5F5),
          margin: EdgeInsets.only(top: 5.h),
          width: MediaQuery.of(context).size.width,
          child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: false,
            physics: const AlwaysScrollableScrollPhysics(),
            header: const ClassicHeader(
              refreshStyle: RefreshStyle.Follow,
              idleText: '下拉刷新',
              refreshingText: '加载中...',
              completeText: '刷新完成',
              failedText: '刷新失败',
              textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
              releaseText: '松开刷新',
              iconPos: IconPosition.top,
              spacing: 8,
            ),
            onRefresh: () => _onRefresh1(),
            controller: _refreshController1,
            child: ListView.builder(
              shrinkWrap: true,
              physics: const AlwaysScrollableScrollPhysics(),
              padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
              itemCount: 1,
              itemBuilder: (context, index) {
                return Column(children: [
                  Padding(padding: EdgeInsets.only(top: 70.h)),
                  Image.asset('assets/images/empty/ic_empty_search.png', width: 150, height: 150),
                  const Text('暂无上新', style: TextStyle(fontSize: 18, color: Colors.grey)),
                ]);
              },
            ),
          ));
    }

    return Flexible(
        child: Container(
            color: const Color(0xFFF5F5F5),
            child: SmartRefresher(
              enablePullDown: true,
              enablePullUp: true,
              physics: const AlwaysScrollableScrollPhysics(),
              header: const ClassicHeader(
                refreshStyle: RefreshStyle.Follow,
                idleText: '下拉刷新',
                refreshingText: '加载中...',
                completeText: '刷新完成',
                failedText: '刷新失败',
                textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
                releaseText: '松开刷新',
                iconPos: IconPosition.top,
                spacing: 8,
              ),
              footer: CustomFooter(
                builder: (BuildContext context, LoadStatus? mode) {
                  Widget body;
                  if (mode == LoadStatus.idle) {
                    body = const Text("上拉加载更多", style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else if (mode == LoadStatus.loading) {
                    body = const Text("加载中...", style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else if (mode == LoadStatus.failed) {
                    body = const Text("加载失败，点击重试", style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else if (mode == LoadStatus.canLoading) {
                    body = const Text("松手加载更多", style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else {
                    body = const Text("没有更多上新了", style: TextStyle(color: Color(0xFF8C8C8C)));
                  }
                  return SizedBox(
                    height: 35.w,
                    child: Center(child: body),
                  );
                },
              ),
              onRefresh: () => _onRefresh2(),
              onLoading: () => _onLoading2(),
              controller: _refreshController2,
              child: ListView.builder(
                shrinkWrap: true,
                physics: const ClampingScrollPhysics(),
                itemCount: _commodityTopList.length,
                itemBuilder: (BuildContext context, int index) {
                  var commodityTop = _commodityTopList[index];
                  var files = commodityTop.files ?? [];
                  return GestureDetector(
                      child: Container(
                          color: const Color(0xFFF5F5F5),
                          width: MediaQuery.of(context).size.width,
                          child: Container(
                              width: MediaQuery.of(context).size.width,
                              margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(8.r)),
                                color: const Color(0xFFFFFFFF),
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      mainAxisSize: MainAxisSize.max,
                                      children: [
                                        RichText(
                                          text: TextSpan(children: [
                                            WidgetSpan(
                                              alignment: PlaceholderAlignment.middle,
                                              child: Padding(
                                                padding: const EdgeInsets.only(left: 10, top: 15, right: 8, bottom: 12),
                                                child: SizedBox(
                                                  height: 40.w,
                                                  width: 40.w,
                                                  child: ClipRRect(
                                                      borderRadius: BorderRadius.circular(50.0),
                                                      child: CachedNetworkImage(
                                                        width: 40.w,
                                                        height: 40.w,
                                                        imageUrl: commodityTop.shopIcon ?? "",
                                                        imageBuilder: (context, imageProvider) => Container(
                                                          decoration: BoxDecoration(
                                                              image: DecorationImage(
                                                                  image: imageProvider, fit: BoxFit.cover)),
                                                        ),
                                                        placeholder: (context, url) => headImage,
                                                        errorWidget: (context, url, error) => headImage,
                                                      )),
                                                ),
                                              ),
                                            ),
                                            TextSpan(
                                                text: commodityTop.shopName ?? "鲁米潮创",
                                                style: const TextStyle(
                                                    fontFamily: "PingFang SC",
                                                    fontWeight: FontWeight.w700,
                                                    fontSize: 16,
                                                    color: Color(0xFF262626))),
                                          ]),
                                        ),
                                        Padding(
                                            padding: const EdgeInsets.only(
                                              left: 8,
                                            ),
                                            child: Text(commodityTop.title ?? "",
                                                style: const TextStyle(
                                                  fontFamily: "PingFang SC",
                                                  fontWeight: FontWeight.w700,
                                                  fontSize: 14,
                                                  color: Color(0xFF262626),
                                                ))),
                                        Padding(
                                          padding: EdgeInsets.only(
                                              left: 16,
                                              top: (commodityTop.content ?? '').isEmpty ? 0 : 8,
                                              right: 8,
                                              bottom: (commodityTop.content ?? '').isEmpty ? 0 : 8),
                                          // child: Text(commodityTop.content ?? '',
                                          //     style: const TextStyle(
                                          //       fontFamily: "PingFang SC",
                                          //       fontWeight: FontWeight.w500,
                                          //       fontSize: 14,
                                          //       color: Color(0xFF262626),
                                          //     ))
                                        ),
                                        Padding(
                                          padding: const EdgeInsets.symmetric(horizontal: 8),
                                          child: Wrap(
                                            spacing: 6.0, // 主轴(水平)方向间距
                                            runSpacing: 8.0, // 纵轴（垂直）方向间距
                                            alignment: WrapAlignment.center,
                                            children: files.isEmpty
                                                ? []
                                                : files.map((file) {
                                                    return Container(
                                                        width: 106.w,
                                                        height: 106.w,
                                                        decoration: BoxDecoration(
                                                          borderRadius: BorderRadius.all(Radius.circular(8.r)),
                                                          color: Colors.white,
                                                        ),
                                                        child: GestureDetector(
                                                          onTap: () {
                                                            final imageProvider = NetworkImage(file ?? "");
                                                            showImageViewer(
                                                              context,
                                                              imageProvider,
                                                              swipeDismissible: false,
                                                              doubleTapZoomable: true,
                                                              onViewerDismissed: () {
                                                                print('图片预览已关闭');
                                                              },
                                                            );
                                                          },
                                                          child: CachedNetworkImage(
                                                              width: 106.w,
                                                              height: 106.w,
                                                              imageUrl: file,
                                                              imageBuilder: (context, imageProvider) => Container(
                                                                    decoration: BoxDecoration(
                                                                        borderRadius:
                                                                            BorderRadius.all(Radius.circular(8.r)),
                                                                        image: DecorationImage(
                                                                            image: imageProvider, fit: BoxFit.cover)),
                                                                  ),
                                                              errorWidget: (context, url, error) =>
                                                                  Image.asset("assets/images/app_icon.png")),
                                                        ));
                                                  }).toList(),
                                          ),
                                        ),
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          mainAxisSize: MainAxisSize.max,
                                          children: [
                                            Padding(
                                                padding: const EdgeInsets.only(left: 16, top: 15, right: 8, bottom: 12),
                                                child: Text(commodityTop.time?.replaceFirst("T", " ") ?? "",
                                                    style: const TextStyle(
                                                      fontFamily: "PingFang SC",
                                                      fontWeight: FontWeight.w500,
                                                      fontSize: 14,
                                                      color: Color(0xFF8C8C8C),
                                                      leadingDistribution: TextLeadingDistribution.even, // 设置leading策略
                                                    ))),
                                            GestureDetector(
                                              behavior: HitTestBehavior.translucent,
                                              child: Padding(
                                                  padding: const EdgeInsets.only(left: 6, right: 16),
                                                  child: RichText(
                                                    text: TextSpan(
                                                      children: [
                                                        ((commodityTop.currentUserSupport ?? 0) == 0
                                                            ? WidgetSpan(
                                                                alignment: PlaceholderAlignment.middle,
                                                                child: Image.asset(
                                                                  "assets/images/ic_heart_unchecked.png",
                                                                  scale: 2,
                                                                ),
                                                              )
                                                            : WidgetSpan(
                                                                alignment: PlaceholderAlignment.middle,
                                                                child: Image.asset("assets/images/ic_heart_checked.png",
                                                                    scale: 2),
                                                              )),
                                                        TextSpan(
                                                            text: ((commodityTop.currentUserSupport ?? 0) == 0
                                                                ? " 点赞"
                                                                : ' ${commodityTop.currentUserSupport}'),
                                                            style: const TextStyle(
                                                                fontFamily: "PingFang SC",
                                                                fontWeight: FontWeight.w500,
                                                                fontSize: 14,
                                                                color: Color(0xFF8C8C8C))),
                                                      ],
                                                    ),
                                                  )),
                                              onTap: () {
                                                _onLike(commodityTop);
                                              },
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ))),
                      onTap: () {
                        var url =
                            "${Constant.H5_BASE_URL}goodsDetailPage.html?goodsid=${commodityTop.commodityId ?? ""}&domain=${Constant.API_BASE_URL}&timestamp=${DateUtil.timestamp()}";
                        EcyRouter.push(context, url, {"h5Title": "商品详情", "h5Url": url});
                      });
                },
              ),
            )));
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController1.dispose();
    _refreshController2.dispose();
  }

  @override
  void deactivate() {
    super.deactivate();
  }
}
